/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.service.project;

import cn.ac.nercis.pes.common.constant.common.TargetConstants;
import cn.ac.nercis.pes.common.utils.DataUtils;
import cn.ac.nercis.pes.common.constant.knowledge.TargetDeepness;
import cn.ac.nercis.pes.common.constant.knowledge.TargetLevel;
import cn.ac.nercis.pes.common.constant.knowledge.TargetType;
import cn.ac.nercis.pes.common.constant.knowledge.VirtualClassification;
import cn.ac.nercis.pes.common.constant.project.SecurityLevel;
import cn.ac.nercis.pes.common.constant.project.SpecialType;
import cn.ac.nercis.pes.model.dto.common.Result;
import cn.ac.nercis.pes.model.dto.common.ResultCode;
import cn.ac.nercis.pes.model.dto.common.TreeNode;
import cn.ac.nercis.pes.model.dto.target.*;
import cn.ac.nercis.pes.repository.dal.evaluation.AssetRepository;
import cn.ac.nercis.pes.repository.dal.evaluation.EvaluationRecordRepository;
import cn.ac.nercis.pes.repository.dal.knowledge.KmTargetRepository;
import cn.ac.nercis.pes.repository.dal.manage.ConstantRepository;
import cn.ac.nercis.pes.repository.dal.project.SystemRepository;
import cn.ac.nercis.pes.repository.dal.project.SystemSpecialTargetRepository;
import cn.ac.nercis.pes.repository.dal.project.SystemTargetRepository;
import cn.ac.nercis.pes.repository.mapper.project.SystemTargetMapper;
import cn.ac.nercis.pes.repository.model.knowledge.KmTargetDO;
import cn.ac.nercis.pes.repository.model.manage.ConstantDO;
import cn.ac.nercis.pes.repository.model.project.SystemDO;
import cn.ac.nercis.pes.repository.model.project.SystemSpecialTargetDO;
import cn.ac.nercis.pes.repository.model.project.SystemTargetDO;
import cn.ac.nercis.pes.service.manage.ProcessRelatedService;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 系统指标管理服务
 *
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
@Service
public record SystemTargetService(SystemRepository systemRepository, SystemTargetRepository systemTargetRepository,
                                  KmTargetRepository kmTargetRepository, ConstantRepository constantRepository,
                                  EvaluationRecordRepository evaluationRecordRepository,
                                  ProcessRelatedService processRelatedService,
                                  SystemSpecialTargetRepository systemSpecialTargetRepository,
                                  AssetRepository assetRepository) {
    private static final String DEFAULT_NOT_APPLY_CONSTANT = "默认不适用指标";
    private static final String NOT_APPLY_CONSTANT_SUFFIX = "_不适用说明";

    @Autowired
    public SystemTargetService {
    }

    public Result<List<LayerTargetDTO>> findLayerTarget(String systemId) {
        SystemDO systemDO = systemRepository.findById(systemId).orElse(null);
        if (Objects.isNull(systemDO)) {
            return Result.failed(ResultCode.SYSTEM_NOT_EXIST);
        }
        if (Objects.isNull(systemDO.getSecurityLevel()) || systemDO.getSecurityLevel() == SecurityLevel.DEFAULT) {
            return Result.failed(ResultCode.SECURITY_LEVEL_UNDEFINED);
        }
        if (SecurityLevel.getSupportLevels().stream().noneMatch(level -> level == systemDO.getSecurityLevel())) {
            return Result.failed(ResultCode.SECURITY_LEVEL_NOT_SUPPORT);
        }
        List<SystemTargetDO> systemTargets = systemTargetRepository.findAllBySystemId(systemId);
        var layerTargets = systemTargets.stream()
                .filter(st -> st.getKmDeepness() == TargetDeepness.LAYER.getDeepness())
                .sorted(Comparator.comparing(SystemTargetDO::getKmSort))
                .map(SystemTargetMapper.INSTANCE::toLayerTargetDTO)
                .peek(lt -> lt.setExistNotApply(systemTargets.stream()
                        .anyMatch(st -> StringUtils.equals(st.getKmParentId(), lt.getTargetId())
                                && !st.getIsApply())))
                .collect(Collectors.toList());
        return Result.success(layerTargets);
    }

    public Result<LayerTargetDTO> getLayerTarget(String systemId, String layerTargetId) {
        SystemDO systemDO = systemRepository.findById(systemId).orElse(null);
        if (Objects.isNull(systemDO)) {
            return Result.failed(ResultCode.SYSTEM_NOT_EXIST);
        }
        List<SystemTargetDO> systemTargets = systemTargetRepository.findAllBySystemId(systemId);
        return systemTargets.stream()
                .filter(st -> st.getKmDeepness() == TargetDeepness.LAYER.getDeepness()
                        && StringUtils.equals(st.getKmTargetId(), layerTargetId))
                .map(SystemTargetMapper.INSTANCE::toLayerTargetDTO)
                .peek(lt -> lt.setExistNotApply(systemTargets.stream()
                        .anyMatch(st -> StringUtils.equals(st.getKmParentId(), lt.getTargetId())
                                && !st.getIsApply())))
                .findFirst()
                .map(Result::success)
                .orElse(Result.failed(ResultCode.NOT_FOUND));
    }

    public List<UnitTargetDTO> findUnitTarget(String systemId, String layerTargetId) {
        List<SystemTargetDO> systemTargets = this.systemTargetRepository.findAllBySystemId(systemId);
        return systemTargets.stream()
                .filter(st -> StringUtils.equals(st.getKmParentId(), layerTargetId))
                .sorted(Comparator.comparing(SystemTargetDO::getKmSort))
                .map(SystemTargetMapper.INSTANCE::toUnitTargetDTO)
                .peek(ut -> {
                    ut.setLayerTarget(this.getTargetNameById(layerTargetId, systemTargets));
                    ut.setEvaTarget(this.getTargetNameByParentId(ut.getTargetId(), systemTargets));
                })
                .collect(Collectors.toList());
    }

    public Result<String> checkRelatedTarget(@NonNull EditApplyTargetDTO applyTarget) {
        SystemTargetDO targetDO = this.systemTargetRepository.findById(applyTarget.getId()).orElse(null);
        if (Objects.isNull(targetDO)) {
            return Result.success();
        }
        boolean existEvalRecord = this.evaluationRecordRepository.existsBySystemIdAndUnitTargetId(applyTarget.getSystemId(), targetDO.getKmTargetId());
        if (!targetDO.getIsApply().equals(applyTarget.getIsApply()) && existEvalRecord) {
            return Result.failed("当前单元指标下存在测评数据，是否继续进行保存？");
        } else {
            return Result.success();
        }
    }

    public Result<String> batchCheckRelatedTarget(List<EditApplyTargetDTO> applyTargets) {
        Result<String> result = Result.success();
        for (EditApplyTargetDTO item : applyTargets) {
            result = checkRelatedTarget(item);
            if (!result.isSuccess()) {
                break;
            }
        }
        return result;
    }

    public Result<String> modifyApplyTarget(@NonNull EditApplyTargetDTO applyTarget) {
        SystemTargetDO targetDO = this.systemTargetRepository.findById(applyTarget.getId()).orElse(null);
        if (Objects.isNull(targetDO)) {
            return Result.failed(ResultCode.NOT_FOUND);
        }
        if (!targetDO.getIsApply().equals(applyTarget.getIsApply())) {
            targetDO.setIsApply(applyTarget.getIsApply());
            processRelatedService.deleteTargetApplyRelatedData(targetDO);
            processRelatedService.resetTargetApplyRelateModuleProcess(targetDO);
        }
        targetDO.setReasons(applyTarget.getReasons());
        targetDO.setModifyTime(LocalDateTime.now());
        return Optional.of(targetDO)
                .map(systemTargetRepository::save)
                .map(SystemTargetDO::getId)
                .map(Result::success)
                .orElse(Result.failed());
    }

    public Result<String> batchModifyApplyTarget(List<EditApplyTargetDTO> applyTargets) {
        Result<String> result = Result.success();
        for (EditApplyTargetDTO item : applyTargets) {
            result = modifyApplyTarget(item);
            if (!result.isSuccess()) {
                result = Result.failed(ResultCode.FAIL);
                break;
            }
        }
        return result;
    }

    public List<TreeNode> findUnitTargetTree(String systemId) {
        List<SystemTargetDO> targets = systemTargetRepository.findAllBySystemId(systemId);
        var specialTargets = systemSpecialTargetRepository.findAllBySystemId(systemId);
        return targets.stream()
                .filter(st -> st.getKmDeepness() == TargetDeepness.LAYER.getDeepness())
                .sorted(Comparator.comparing(SystemTargetDO::getKmSort))
                .map(st -> TreeNode.builder()
                        .id(st.getKmTargetId())
                        .name(st.getKmName())
                        .children(findUnitTargetTree(st.getKmTargetId(), targets, specialTargets))
                        .data(SystemTargetMapper.INSTANCE.toLayerTargetDTO(st))
                        .build())
                .collect(Collectors.toList());
    }

    public List<TreeNode> findUnitTargetTree(String systemId,String assetId){
        var assetDo = assetRepository.findById(assetId).orElse(null);
        if(Objects.isNull(assetDo)){
            return Collections.emptyList();
        }
        var virtualClass = VirtualClassification.fromClassId(assetDo.getClassId());
        var treeNodes = findUnitTargetTree(systemId);
        if(virtualClass != VirtualClassification.SECURITY_MANAGE){
            return treeNodes.stream()
                    .filter(tn->StringUtils.equals(tn.getName(),virtualClass.getName()))
                    .toList();
        }else{
            return treeNodes.stream()
                    .filter(tn-> {
                        if (tn.getData() instanceof LayerTargetDTO st) {
                            return st.getType() == TargetType.MANAGEMENT && StringUtils.startsWith(assetDo.getName(), st.getName());
                        } else {
                            return false;
                        }
                    })
                    .toList();
        }
    }

    public void initSystemTarget(SystemDO systemDO) {
        var notApplyConstants = constantRepository.findAllByNameOrderBySort(DEFAULT_NOT_APPLY_CONSTANT);
        var targets = this.kmTargetRepository.findAllByLevel(TargetLevel.fromLevel(systemDO.getSecurityLevel().getLevel()))
                .stream()
                .map(kt -> {
                    SystemTargetDO targetDO = toSystemTarget(systemDO.getId(), kt);
                    setDefaultIsApply(targetDO, kt, notApplyConstants);
                    return targetDO;
                })
                .peek(st -> st.setCreateTime(LocalDateTime.now()))
                .collect(Collectors.toList());
        this.systemTargetRepository.saveAll(targets);
    }

    public void deleteSystemTargetBySystemId(@NonNull String systemId) {
        systemTargetRepository.deleteAllBySystemId(systemId);
    }

    public void repairSystemTargetRef() {
        this.systemRepository.findAll().forEach(sys -> repairSystemTargetRef(sys.getId()));
    }

    public SpecialTargetConfigDTO getSpecialTargetConfig(String systemId, String layerTargetId){
        var sourceTarget = this.systemTargetRepository.findBySystemIdAndKmTargetId(systemId, layerTargetId)
                .orElse(null);
        if (Objects.isNull(sourceTarget) || sourceTarget.getKmLevel() == TargetLevel.G4) {
            return SpecialTargetConfigDTO.builder().build();
        }
        var sourceTargets = this.systemTargetRepository.findAllBySystemId(systemId);
        var unitTargetSources = sourceTargets
                .stream()
                .filter(ut -> StringUtils.equals(ut.getKmParentId(), layerTargetId))
                .sorted(Comparator.comparingInt(SystemTargetDO::getKmSort))
                .map(st -> SpecialTargetDTO.builder()
                        .id(st.getKmTargetId())
                        .name(st.getKmName())
                        .type(st.getKmType())
                        .level(st.getKmLevel())
                        .sort(st.getKmSort())
                        .applyClaim(st.getKmApplyClaim())
                        .targetDesc(sourceTargets.stream()
                                .filter(dt->StringUtils.equals(dt.getKmParentId(), st.getKmTargetId()))
                                .map(SystemTargetDO::getKmName)
                                .findFirst()
                                .orElse(StringUtils.EMPTY))
                        .build())
                .toList();
        var upLevels = Stream.of(TargetLevel.values())
                .filter(l->l.getTargetLevel()>sourceTarget.getKmLevel().getTargetLevel())
                .toList();
        return SpecialTargetConfigDTO.builder()
                .sources(unitTargetSources)
                .upLevels(upLevels)
                .upgrades(findUpgradeTargets(upLevels,sourceTarget))
                .build();
    }

    private List<SpecialTargetDTO> findUpgradeTargets(List<TargetLevel> levels,SystemTargetDO layerTarget){
        if(CollectionUtils.isEmpty(levels)){
            return Collections.emptyList();
        }
        return levels.stream()
                .flatMap(item->findUpgradeTargets(item,layerTarget).stream())
                .toList();
    }

    private List<SpecialTargetDTO> findUpgradeTargets(TargetLevel level,SystemTargetDO layerTarget){
        var upgradeTargets = kmTargetRepository.findAllByLevel(level);
        var upLayerTarget = upgradeTargets.stream()
                .filter(kt -> kt.getDeepness().equals(layerTarget.getKmDeepness())
                        && StringUtils.equals(kt.getName(), layerTarget.getKmName()))
                .findFirst()
                .orElse(null);
        if (Objects.isNull(upLayerTarget)) {
            return Collections.emptyList();
        }
        return upgradeTargets.stream()
                .filter(ut -> StringUtils.equals(ut.getParentId(), upLayerTarget.getId()))
                .sorted(Comparator.comparingInt(KmTargetDO::getSort))
                .map(kt -> SpecialTargetDTO.builder()
                        .id(kt.getId())
                        .name(kt.getName())
                        .type(kt.getType())
                        .level(kt.getLevel())
                        .sort(kt.getSort())
                        .applyClaim(kt.getApplyClaim())
                        .targetDesc(upgradeTargets.stream()
                                .filter(dt->StringUtils.equals(dt.getParentId(), kt.getId()))
                                .map(KmTargetDO::getName)
                                .findFirst()
                                .orElse(StringUtils.EMPTY))
                        .build())
                .toList();
    }

    public List<UnitSpecialTargetDTO> findUnitSpecialTargets(String systemId, String layerTargetId){
        return this.systemSpecialTargetRepository.findAllBySystemIdAndLayerTargetId(systemId, layerTargetId)
                .stream()
                .sorted(Comparator.comparingInt(SystemSpecialTargetDO::getSort))
                .map(SystemTargetMapper.INSTANCE::toUnitSpecialTargetDTO)
                .toList();
    }

    public Result<String> saveSpecialTarget(EditSpecialTargetDTO specialTarget){
        if(StringUtils.isBlank(specialTarget.getId())){
            return createSpecialTarget(specialTarget);
        }else {
            return modifySpecialTarget(specialTarget);
        }
    }

    public Result<String> batchSaveSpecialTarget(List<EditSpecialTargetDTO> data){
        Result<String> result = Result.success();
        for(EditSpecialTargetDTO item : data){
            Result<String> itemResult = saveSpecialTarget(item);
            if(!itemResult.isSuccess()){
                result = Result.failed(ResultCode.FAIL);
                break;
            }
        }
        return result;
    }

    public Result<String> deleteSpecialTarget(String id){
        try{
            return this.systemSpecialTargetRepository.findById(id)
                    .map(entity -> {
                        processRelatedService.deleteSpecialTargetRelatedData(entity.getSystemId(),id);
                        systemSpecialTargetRepository.delete(entity);
                        return entity;
                    })
                    .map(SystemSpecialTargetDO::getId)
                    .map(Result::success)
                    .orElse(Result.failed());
        }catch (Exception ex){
            log.error("删除特殊指标信息出错：",ex);
            return Result.failed();
        }
    }

    public Result<String> batchDeleteSpecialTarget(Set<String> ids){
        Result<String> result = Result.success();
        for(String id : ids){
            Result<String> itemResult = deleteSpecialTarget(id);
            if(!itemResult.isSuccess()){
                result = Result.failed(ResultCode.FAIL);
                break;
            }
        }
        return result;
    }

    private Result<String> createSpecialTarget(EditSpecialTargetDTO specialTarget){
        var specialTargetList = this.systemSpecialTargetRepository.findAllBySystemId(specialTarget.getSystemId())
                .stream()
                .filter(st -> StringUtils.equals(specialTarget.getLayerTargetId(), st.getLayerTargetId()))
                .toList();
        if (specialTargetList.stream().anyMatch(st -> StringUtils.equals(st.getName(), specialTarget.getName()))) {
            return Result.failed("已存在相同名称的特殊指标！");
        }
        var lastSort = specialTargetList.stream()
                .max(Comparator.comparingInt(SystemSpecialTargetDO::getSort))
                .map(SystemSpecialTargetDO::getSort)
                .orElse(0);
        var entity = SystemSpecialTargetDO.builder()
                .systemId(specialTarget.getSystemId())
                .layerTargetId(specialTarget.getLayerTargetId())
                .name(specialTarget.getName())
                .specialType(specialTarget.getSpecialType())
                .targetDesc(specialTarget.getTargetDesc())
                .reasons(specialTarget.getReasons())
                .kmApplyClaim(specialTarget.getApplyClaim())
                .sort(lastSort+1)
                .kmLevel(TargetLevel.DEFAULT)
                .kmType(TargetType.DEFAULT)
                .build();
        if(specialTarget.getSpecialType() != SpecialType.CUSTOM){
            kmTargetRepository.findById(specialTarget.getKmTargetId())
                    .ifPresent(refTarget->{
                        entity.setKmTargetId(refTarget.getId());
                        entity.setKmApplyClaim(refTarget.getApplyClaim());
                        entity.setKmDeepness(refTarget.getDeepness());
                        entity.setKmIsSpecial(refTarget.getIsSpecial());
                        entity.setKmScore(refTarget.getScore());
                        entity.setKmLevel(refTarget.getLevel());
                        entity.setKmType(refTarget.getType());
                        entity.setKmWeight(refTarget.getWeight());
                    });
        }
        entity.setCreateTime(LocalDateTime.now());
        return Optional.of(entity)
                .map(systemSpecialTargetRepository::save)
                .map(SystemSpecialTargetDO::getId)
                .map(Result::success)
                .orElse(Result.failed());
    }

    private Result<String> modifySpecialTarget(EditSpecialTargetDTO specialTarget){
        var source = this.systemSpecialTargetRepository.findById(specialTarget.getId()).orElse(null);
        if(Objects.isNull(source)){
            return Result.failed(ResultCode.NOT_FOUND);
        }
        return Optional.of(source)
                .map(s->{
                    if(specialTarget.getSpecialType() == SpecialType.CUSTOM){
                        s.setName(specialTarget.getName());
                        s.setKmApplyClaim(specialTarget.getApplyClaim());
                        s.setTargetDesc(specialTarget.getTargetDesc());
                    }
                    s.setReasons(specialTarget.getReasons());
                    s.setModifyTime(LocalDateTime.now());
                    return s;
                })
                .map(systemSpecialTargetRepository::save)
                .map(SystemSpecialTargetDO::getId)
                .map(Result::success)
                .orElse(Result.failed());
    }

    public void reInitSystemTarget(@NonNull String systemId, @NonNull SecurityLevel securityLevel) {
        //移除关联的旧级别指标并重新初始化新级别指标
        deleteSystemTargetBySystemId(systemId);
        List<ConstantDO> notApplyConstants = constantRepository.findAllByNameOrderBySort(DEFAULT_NOT_APPLY_CONSTANT);
        List<SystemTargetDO> targets = this.kmTargetRepository.findAllByLevel(TargetLevel.fromLevel(securityLevel.getLevel()))
                .stream()
                .map(kt -> {
                    SystemTargetDO targetDO = toSystemTarget(systemId, kt);
                    setDefaultIsApply(targetDO, kt, notApplyConstants);
                    return targetDO;
                })
                .peek(st -> st.setCreateTime(LocalDateTime.now()))
                .collect(Collectors.toList());
        this.systemTargetRepository.saveAll(targets);
    }

    private void repairSystemTargetRef(@NonNull String systemId) {
        Map<String, KmTargetDO> targetCaches = new LinkedHashMap<>();
        var systemTargets = this.systemTargetRepository.findAllBySystemId(systemId)
                .stream()
                .filter(st -> StringUtils.isBlank(st.getKmName()))
                .peek(st -> repairSystemTargetRef(st, getKmTarget(st.getKmTargetId(), targetCaches)))
                .toList();
        if (CollectionUtils.isNotEmpty(systemTargets)) {
            this.systemTargetRepository.saveAllAndFlush(systemTargets);
        }
    }

    private void repairSystemTargetRef(SystemTargetDO st, KmTargetDO kt) {
        st.setKmApplyClaim(kt.getApplyClaim());
        st.setKmDeepness(kt.getDeepness());
        st.setKmIsSpecial(kt.getIsSpecial());
        st.setKmLevel(kt.getLevel());
        st.setKmName(kt.getName());
        st.setKmParentId(kt.getParentId());
        st.setKmScore(kt.getScore());
        st.setKmSort(kt.getSort());
        st.setKmType(kt.getType());
        st.setKmWeight(kt.getWeight());
    }


    private KmTargetDO getKmTarget(String targetId, Map<String, KmTargetDO> targetCaches) {
        var target = targetCaches.getOrDefault(targetId, null);
        if (Objects.isNull(target)) {
            target = kmTargetRepository.findById(targetId).orElse(null);
            if (Objects.nonNull(target)) {
                targetCaches.put(targetId, target);
            }
        }
        return target;
    }

    private SystemTargetDO toSystemTarget(String systemId, KmTargetDO kt) {
        return SystemTargetDO.builder()
                .systemId(systemId)
                .kmTargetId(kt.getId())
                .kmApplyClaim(kt.getApplyClaim())
                .kmDeepness(kt.getDeepness())
                .kmIsSpecial(kt.getIsSpecial())
                .kmLevel(kt.getLevel())
                .kmName(kt.getName())
                .kmParentId(kt.getParentId())
                .kmScore(kt.getScore())
                .kmSort(kt.getSort())
                .kmType(kt.getType())
                .kmWeight(kt.getWeight())
                .build();
    }

    private List<TreeNode> findUnitTargetTree(String layerTargetId, List<SystemTargetDO> targets, List<SystemSpecialTargetDO> specialTargets) {
        var unitTargets = targets.stream()
                .filter(st -> StringUtils.equals(st.getKmParentId(), layerTargetId))
                .sorted(Comparator.comparing(SystemTargetDO::getKmSort))
                .map(st -> TreeNode.builder()
                        .id(st.getKmTargetId())
                        .name(st.getKmName())
                        .data(SystemTargetMapper.INSTANCE.toUnitTargetDTO(st))
                        .build())
                .toList();
        var specialUnitTargets = specialTargets.stream()
                .filter(st-> StringUtils.equals(st.getLayerTargetId(), layerTargetId))
                .sorted(Comparator.comparingInt(SystemSpecialTargetDO::getSort))
                .map(st -> TreeNode.builder()
                        .id(st.getId())
                        .name(st.getName())
                        .data(SystemTargetMapper.INSTANCE.toUnitSpecialTargetDTO(st))
                        .build())
                .toList();
        return Stream.concat(unitTargets.stream(),specialUnitTargets.stream())
                .toList();
    }

    private void setDefaultIsApply(SystemTargetDO systemTargetDO, @NonNull KmTargetDO targetDO, @NonNull List<ConstantDO> notApplyConstants) {
        if (notApplyConstants.stream().noneMatch(c -> StringUtils.contains(c.getValue(), targetDO.getName()))
                || StringUtils.isBlank(targetDO.getParentId())) {
            systemTargetDO.setIsApply(true);
            return;
        }
        KmTargetDO parentTarget = kmTargetRepository.findById(targetDO.getParentId()).orElse(null);
        if (Objects.isNull(parentTarget)) {
            systemTargetDO.setIsApply(true);
            return;
        }
        var targetName = parentTarget.getName().concat(TargetConstants.MULTI_TARGET_SPLIT).concat(targetDO.getName());
        systemTargetDO.setIsApply(notApplyConstants.stream().noneMatch(c -> StringUtils.equals(c.getValue(), targetName)));
        if (!systemTargetDO.getIsApply()) {
            systemTargetDO.setReasons(DataUtils.findFirst(constantRepository.findByName(targetName.concat(NOT_APPLY_CONSTANT_SUFFIX)))
                    .map(ConstantDO::getValue)
                    .orElse(""));
        }
    }

    private String getTargetNameById(String targetId, List<SystemTargetDO> systemTargets) {
        return systemTargets.stream()
                .filter(st -> StringUtils.equals(st.getKmTargetId(), targetId))
                .map(SystemTargetDO::getKmName)
                .findFirst()
                .orElse("");
    }

    private String getTargetNameByParentId(String parentTargetId, List<SystemTargetDO> systemTargets) {
        return systemTargets.stream()
                .filter(st -> StringUtils.equals(st.getKmParentId(), parentTargetId))
                .map(SystemTargetDO::getKmName)
                .findFirst()
                .orElse("");
    }


}